package yja.gzw.app.activity

import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import yja.gzw.app.R
import yja.gzw.app.adapter.FabuAdapter
import yja.gzw.app.base.BaseActivity
import yja.gzw.app.databinding.ActivityJingpingshipingfabuBinding
import yja.gzw.app.model.UserData
import yja.gzw.app.viewmodel.Mainviewmodel
import com.google.android.material.bottomsheet.BottomSheetDialog
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.util.Calendar

class JingpingshipingfabuActivity :BaseActivity<Mainviewmodel, ActivityJingpingshipingfabuBinding>(R.layout.activity_jingpingshipingfabu), FabuAdapter.OnItemClickListener{
    private lateinit var fabiada: FabuAdapter
    private lateinit var bottomSheetDialog: BottomSheetDialog
    public var list= mutableListOf<ZaoShuju>(
        ZaoShuju(2,""),

        )
    var imgges= mutableListOf<String>()
    var shijian=""
    var zungtai=1
    var file: File?=null


    private fun showTimePickerDialog() {
        val calendar = Calendar.getInstance()
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)

        val timePickerDialog = TimePickerDialog(
            this,
            { _, selectedHour, selectedMinute ->
                val selectedTime = String.format("%02d:%02d", selectedHour, selectedMinute)
              // TODO 设置时间
            },
            hour,
            minute,
            true
        )
        timePickerDialog.show()
    }

    private fun showDatePickerDialog() {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        val datePickerDialog = DatePickerDialog(
            this,
            { _, selectedYear, selectedMonth, selectedDayOfMonth ->
                val selectedDate = String.format("%d-%02d-%02d", selectedYear, selectedMonth + 1, selectedDayOfMonth)

                binding.shijianxuanzeqi.text=selectedDate

            },
            year,
            month,
            day
        )
        datePickerDialog.show()
    }


    override fun initView() {

        binding.shijianxuanzeqi.setOnClickListener {

//            bottomSheetDialog = BottomSheetDialog(this)
//            val view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_shijianxunzqi, null)
//            bottomSheetDialog.setContentView(view)
//            bottomSheetDialog.show()
            showDatePickerDialog()


        }


        binding.jiageshurukuang.isEnabled=false
        //todo 发布按钮
        binding.fabuanniu.setOnClickListener {
            viewmodel.onisqiyebangdingwang(UserData.token)

        }
        binding.pingtaixuanze.setOnClickListener {

            bottomSheetDialog = BottomSheetDialog(this)
            val view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_shipingmoshi, null)
            bottomSheetDialog.setContentView(view)

            val chahao =view.findViewById<ImageView>(R.id.chacha)
            val quxiao =view.findViewById<TextView>(R.id.quxiao)
            val queding =view.findViewById<TextView>(R.id.queding)
            val xuai1 =view.findViewById<RadioButton>(R.id.xuan1)
            val xuai2 =view.findViewById<RadioButton>(R.id.xuan2)
            val xuai3 =view.findViewById<RadioButton>(R.id.xuan3)


            //TODO确定按钮
            queding.setOnClickListener {

                if(xuai1.isChecked){
                    zungtai=1
                    binding.jiageshurukuang.hint="请输入价格，最低￥40   "
                    binding.moshiziti.text="自己定价"
                    binding.jiageshurukuang.isEnabled=true
                    binding.jiageshurukuang.text=null
                    binding.xuanzejingjieshijian.visibility= View.GONE
                }else if(xuai2.isChecked){
                    binding.moshiziti.text="第二方定价"
                    zungtai=2
                    binding.jiageshurukuang.setText("第二方出价，双方确认")
                    binding.jiageshurukuang.isEnabled=false
                    binding.xuanzejingjieshijian.visibility= View.GONE
                }else{
                    zungtai=3
                    binding.moshiziti.text="第二方竞价"

                    binding.jiageshurukuang.setText("第二方竞价，价底者得")

                    binding.jiageshurukuang.isEnabled=false
                    binding.xuanzejingjieshijian.visibility= View.VISIBLE
                }


                bottomSheetDialog.dismiss()

            }

            chahao.setOnClickListener {
                bottomSheetDialog.dismiss()

            }

            quxiao.setOnClickListener {
                bottomSheetDialog.dismiss()

            }

            bottomSheetDialog.show()

        }



        binding.review.layoutManager=
            GridLayoutManager(this, 3)
        fabiada= FabuAdapter(this,list,this)
        binding.review.adapter= fabiada
    }

    override fun dataObservese() {

        viewmodel.onfabujingpingshiping.observe(this, Observer {
            if(it.code==1){
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()
                finish()
            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()

            }


        })
        viewmodel.onisqiyebangding.observe(this, Observer {
            if(it.code==1){
                if(it.data.is_bind!=2){
                    Toast.makeText(this, "请先绑定企业", Toast.LENGTH_SHORT).show()
                    val inten=Intent(this,QiyebangdingActivity::class.java)
                    startActivity(inten)

                }else{
                   // Toast.makeText(this, "已通过", Toast.LENGTH_SHORT).show()

                    val title=binding.biaoti.text.toString()
                    val beizhu=binding.beizhu.text.toString()
                    var tutus=""
                    for ((index, value) in imgges.withIndex()) {
                        if(index==imgges.size-1){

                            tutus= tutus+value
                        }else{
                            tutus= tutus+value+","

                        }

                    }
                    Log.e("图片详情",tutus)
                    val jiage=binding.jiageshurukuang.text.toString()
                    shijian=binding.shijianxuanzeqi.text.toString()


                    viewmodel.onfabujingpingshipingwang(UserData.token,mapOf("title" to title,"fine_release_type" to zungtai.toString(),"endtime" to shijian,"remark" to beizhu,"material" to tutus,"pay_price" to jiage))

                }

            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()

            }

        })

        viewmodel.onlusc.observe(this, Observer {
            if(it.code==1){



                list.add(0,ZaoShuju(1,it.data.url))
                Log.e("上传图片的半路径",it.data.url)
                binding.review.layoutManager=
                    GridLayoutManager(this, 3)
                fabiada= FabuAdapter(this,list,this)
                binding.review.adapter= fabiada
                imgges.add(it.data.url)
                Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show()




            }


        })
    }

    override fun onItemClick(position: Int, uri: ZaoShuju) {
        if(uri.leixing==2){
            openGallery()

        }else{
            Toast.makeText(this, "图片预览中"+"    "+list.size, Toast.LENGTH_SHORT).show()


        }
    }

    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, GALLERY_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            data?.data?.let { uri ->
                file = File(getRealPathFromURI(uri))

                val requestFile = file?.asRequestBody("multipart/form-data".toMediaTypeOrNull())
                val body = MultipartBody.Part.createFormData("file", file?.name,requestFile!!)
                viewmodel.onluying(body)
            }
        }
    }

    private fun getRealPathFromURI(contentUri: Uri): String {
        val projection = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = contentResolver.query(contentUri, projection, null, null, null)
        val column_index = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        cursor?.moveToFirst()
        val result = cursor?.getString(column_index!!)
        cursor?.close()
        return result!!
    }
    companion object {
        private const val GALLERY_REQUEST_CODE = 1001
    }


}